var DocData={
    goodsId:'',
    baseData:{},
    initBase:function(data){
        var _data = data
        $('input[name=goodsName]').val(_data.goodsName)
        $('input[name=goodsIncomeRatio]').val(_data.goodsIncomeRatio)
        $('input[name=goodsCost]').val(_data.goodsCost)
        $('img.imghead').attr('src',_data.goodsImg)
    },
    initGoodsCostList:function(data){
        var _upData = data
        $.get(baseUrl.base+baseUrl.init+'selectOrderList',_upData,function(res){
            var _tempDivTxt='';
            if(res.code == 0){
                var _goodistData=res.results.goodList
                for(var i=0;i<_goodistData.length;i++){
                 _tempDivTxt+='<div class="home_fast_storage_detail">\
                                 <img class="home_fast_storage_detail_img" src="'+_goodistData[i].goodsImg+'">\
                                 <p class="home_fast_storage_sum">'+_goodistData[i].goodsName+'</p>\
                                 <p class="home_fast_storage_name"><span>'+_goodistData[i].goodsNumber+'份</span> </p>\
                             </div>';
                }
                if(_goodistData.length == 0){
                    _tempDivTxt += '<div class="nolist"><p>暂无数据</p></div>';
                }
                $('.totallist').html(_tempDivTxt)

                $('.js_total').text(res.results.total)
                $('.js_totalSize').text(_goodistData.length)
            }else{

            }

         },'json')
         if(_upData.ifMonth == '0' ){
             var _date = _upData.orderTime.slice(-2) + "日"
            $('.js_costDate').text(_date)
         }else{
            var _date = _upData.orderTime.substring(5,7) + "月"
            $('.js_costDate').text(_date)
         }
    },
    initGoodsCostDetail:function(data){
        var _upData = data
        if(goodscost == ''){
            goodscost = baseFn.rpDataTables('.js_goodscost_list',{
                ajUrl:baseUrl.base+baseUrl.init+'selectOrderListDetail',
                // ajUrl:baseUrl.base+baseUrl.patient+'selectSysPatientList',
                ajDataSrc:"results",
                ajData:_upData,
                select:false,
                scrollY:windowOffsetData.tableHeight(),
                autoWidth:false,
                columns:[
                    { "data": "doctorId",defaultContent:'',width:"18%",className:'bespeak_change_one img2p',render:function(data,type,row, meta){
                        var _img=baseUrl.tempHeadImg
                        if(baseFn.notNull(row.userImg)){
                            _img = row.userImg
                        }
                        // return '<img class="bespeak_change_img" src="'+row.userImg+'">\
                        return '<div class="datatable_img_div" data-vals="'+_img+'" style="background-image:url('+_img+')"></div>\
                                <div class="bespeak_change_name">\
                                    <span>'+row.userNo+'</span>\
                                    <span>'+row.userName+'</span>\
                                </div>'
                    }},
                    { "data": "subclinicName",defaultContent:'',width:"18%"},
                    { "data": "goodsName",defaultContent:'',width:"18%",className:'bespeak_change_one img2p',render:function(data,type,row, meta){
                        return '<img class="bespeak_change_img" src="'+row.goodsImg+'">\
                                <div class="bespeak_change_name">\
                                    <span>'+data+'</span>\
                                    <span>￥'+row.goodsCost+'</span>\
                                </div>'
                    }},
                    { "data": "orderNum",width:"18%",defaultContent:'无'},
                    { "data": "createTimeStr",width:"20%",defaultContent:'无'}
                ],
                initComplete:function(){
                },
                drawCallback: function( settings ) {
                    //图片初始化
                    $('.js_goodscost_list .datatable_img_div').each(function(ids,val){
                        baseFn.imgSize({
                            src: $(val).data('vals'),
                            hFn: function(res) {
                                res.dom.css({'background-size':'auto 100%'})
                            },
                            wFn: function(res) {
                                res.dom.css({'background-size':'100% auto'})
                            },
                            ratio: 1,
                            otherData: {
                                dom:$(val)
                            }
                        })
                    })
                }
            })
        }else{
            goodscost.settings()[0].ajax.data=_upData
            goodscost.ajax.reload()
        }
    },
    editURL:'/xrtn-manager/init/gotoGoodsSettingAdd',
    baseURL:'/xrtn-manager/init/gotoGoodsSetting'
}

$('.zcsearch_input').val($.session.get("goodName"));

if($('.js_goods_edit').length == 1){
    //判断编辑还是新增
    var _upDatas={},editPostUrl='saveGoodsInfo',postSuccessTxt='成功新增商品'
    if(baseFn.getQueryString('goodsId') != null){
        DocData.goodsId = baseFn.getQueryString('goodsId')
        $('.js_line_last').text('编辑商品')
        _upDatas.goodsId=DocData.goodsId
        editPostUrl = 'updateGoodsInfo',
        postSuccessTxt='商品修改成功'
        $('.edit_up').removeClass('hidden')
    }
    //编辑
    if(DocData.goodsId != ''){
        $.get(baseUrl.base+baseUrl.init+'selectGoodsInfo',_upDatas,function(res){
            if(res.code == 0){
                DocData.baseData = res.results
                DocData.initBase(res.results)
                $('input[name=imgurl]').val(res.results.goodsImg)
                DocData.imgChange = true
            }
        },'json')
    }
    /*组件初始化*/
    // baseFn.rpSelect('.userAddSubclinic',{
    //     url:baseUrl.base+baseUrl.subclinic+'selectSubclinicList',
    //     idKey:'subclinicId',
    //     textKey:'subclinicName',
    //     selFn:function(){
    //     }
    // })

    //图片上传
    $('.imghead').on('click',function(){
        $('#Js_previewImgNew').trigger('click')
    })
    function zcuploadImageCover(e){
        baseFn.imgUpload($(e).parents('form').attr('id'),function(res){
            $(e).siblings('.Js_preview').find('img').attr('src',res.url)
            DocData.imgChange=true;
            $('input[name=imgurl]').val(res.url)
        })
    }
    var myValidform = $(".js_goods_edit").Validform({
        tiptype:2,
        datatype:{
            nRatio:function(gets,obj,curform,regxp){
                var _n = Number(gets);
                console.log(_n>=0 && _n<=100 && regxp['n'].test(_n))
                return (_n>=0 && _n<=100 && regxp['n'].test(_n));
            },
            putso:function(gets,obj,curform,regxp){
                /*参数gets是获取到的表单元素值，
                  obj为当前表单元素，
                  curform为当前验证的表单，
                  regxp为内置的一些正则表达式的引用。*/
                var _checkpwrap = obj.parents('.checkpwrap')
                var _type = _checkpwrap.find('.checkp').val()
                var _userid = _checkpwrap.find('.userid').val()
                var _post = _checkpwrap.find('.post').val()
                var reg1=regxp["*"],
                    reg2=/[\d]{7}/,
                    mobile=curform.find(".mobile");
                if(obj){
                    if(_type == '1'){
                        //人
                        //console.log(_userid)
                        if(reg1.test(_userid)){return true;}
                    }else if(_type == '3'){
                        //岗位
                        if(reg1.test(_post)){return true;}
                    }
                }
                return false;
            },
            ztreegroup:function(gets,obj,curform,regxp){
                console.log(gets)
                if(gets == ''){
                    return false
                }else{
                }
            },
            select2:function(gets,obj,curform,regxp){
                if(gets.length ==0){
                    obj.siblings('.select2').find('.select2-selection').css('borderColor','red')
                    return false
                }else{
                    obj.siblings('.select2').find('.select2-selection').css('borderColor','#ccc')
                }
            }
        }
    });
    /*组件初始化*/
    $('.js_goods_edit .edit_ok').on('click',function(){
        if(!myValidform.check()){
            return false
        }
        _upDatas.goodsName=$('input[name=goodsName]').val();
        _upDatas.goodsIncomeRatio=0.1;//暂时比例定死
        // _upDatas.goodsIncomeRatio=$('input[name=goodsIncomeRatio]').val();
        _upDatas.goodsCost=$('input[name=goodsCost]').val();
        if(DocData.imgChange){
            _upDatas.goodsImg=$('img.imghead').attr('src')
        }else{
            baseFn.dialog({
                title:'失败',
                content:'请传图片'
            })
        }
        // return false
        $.post(baseUrl.base+baseUrl.init+editPostUrl,_upDatas,function(res){
            if(res.code == '0'){
                if (editPostUrl == "saveGoodsInfo") {
                    DocData.goodsId=res.results;
                }
                if(baseFn.getQueryString('goodsId') != null){
                    baseFn.infoDialog(postSuccessTxt)
                }else{
                    $('.edit_up').removeClass('hidden')
                    baseFn.dialog({
                        title:'添加成功',
                        content:'商品添加成功，是否直接上架？',
                        ok:function(){
                            $.post(baseUrl.base+baseUrl.init+'updateGoodsInfo',{goodsState:1,goodsId:DocData.goodsId},function(res){
                                if(res.code == '0'){
                                    baseFn.infoDialog('上架成功')
                                    baseFn.goPath('gotoGoodsSetting')
                                }else{
                                    baseFn.infoDialog(res.info)
                                }
                            },'json')
                        },
                        cancel:function(){

                        }
                    })
                }
            }else{
                baseFn.infoDialog(res.info)
            }
        },'json')
    })
    $('.js_goods_edit .edit_up').on('click',function(){
        if(!myValidform.check()){
            return false
        }
        var _upDatas={
            goodsState:1,
            goodsId:DocData.goodsId,
            goodsName:$('input[name=goodsName]').val(),
            goodsImg:$('img.imghead').attr('src'),
            goodsCost:$('input[name=goodsCost]').val()
        }
        baseFn.dialog({
            title:'上架商品',
            content:'确定上架该商品么？',
            ok:function(){
                $.post(baseUrl.base+baseUrl.init+'updateGoodsInfo',_upDatas,function(res){
                    if(res.code == '0'){
                        baseFn.infoDialog('上架成功')
                        baseFn.goPath('gotoGoodsSetting')
                        // $('.edit_up a').text('下架')
                    }else{
                        baseFn.infoDialog(res.info)
                    }
                },'json')
            },
            cancel:true
        })

    })
}

var orderListDTdata = {
    goodsName: $.session.get("goodName"),
}

// 导出商品销售统计
$('#exportGoodsStat').on('click',function(){
    if (baseFn.getPower(86)) {
        baseFn.infoDialog('您没有权限使用功能！')
        return false
    }
    var subclinicId = $('.subclinic').val();
    var ifMonth = $('.timetype').val();
    var orderTime = $('.timeday').val();

    window.open(baseUrl.base+"excel/exportOrderList?subclinicId="+subclinicId+"&ifMonth="+ifMonth+"&orderTime="+orderTime, "_blank");
});

if($('.js_goods_list').length != 0){
    var goods = baseFn.rpDataTables('.js_goods_list',{
        ajUrl:baseUrl.base+baseUrl.init+'selectInitGoodsList',
        ajDataSrc:"results",
        ajType:'get',
        ajData:orderListDTdata,
        sessionPageKey: "goodsPage",
        scrollY:windowOffsetData.tableHeight(),
        autoWidth:false,
        columns:[
            { "data": "goodsName",width:"30%",defaultContent:'',className:'imgpwrap img2p',render:function(data,type,row, meta){
                var _img=baseUrl.tempHeadImg
                if(baseFn.notNull(row.goodsImg)){
                    _img = row.goodsImg
                }
                // return '<img class="bespeak_change_img" src="'+row.goodsImg+'">\
                return '<div class="datatable_img_div" data-vals="'+_img+'" style="background-image:url('+_img+')"></div>\
                                        <div class="bespeak_change_name">\
                                            <span>'+data+'</span>\
                                            <span>'+row.goodsCost+'</span>\
                                        </div>'
            }},
            { "data": "orderNumber",width:"50%",defaultContent:''},
            { "data": "goodsState",defaultContent:'无',width:"15%",render:function(data,type,row, meta){
                if (data == 1){
                    return '<a href="javascript:void(0)" class="datatablebtn datatablebtnRed remove" data-vals="'+row.goodsId+'">下架</a>';
                }else{
                    return '<a href="javascript:void(0)" class="datatablebtn datatablebtnRed up" data-vals="'+row.goodsId+'">上架</a> <a href="javascript:void(0)" class="datatablebtn edit" data-vals="'+row.goodsId+'">编辑</a>';
                }

            }}
        ],
        initComplete:function(){


        },
        page:function () {

        },
        drawCallback: function( settings ) {
            $('.remove').off('click').on('click',function(){
                var _id = $(this).data('vals')
                var _tr = $(this).parents('tr')
                var _upDatas = {
                    goodsId:_id,
                    goodsState:0
                }
                baseFn.dialog({
                    title:'下架商品',
                    content:'确定下架该商品么？',
                    ok:function(){
                        $.post(baseUrl.base+baseUrl.init+'updateGoodsInfo',_upDatas,function(res){
                            var _txt = '下架成功'
                            if(res.code == 0){
                                _txt = '下架成功'
                                var _d = goods.row(_tr).data()
                                _d.goodsState=0
                                goods.row(_tr).data(_d).draw(false)
                            }else{
                                _txt = res.info
                            }
                            baseFn.infoDialog(_txt)
                        },'json')
                    },
                    cancel:true
                })
            })
            $('.up').off('click').on('click',function(){
                var _id = $(this).data('vals')
                var _tr = $(this).parents('tr')
                var _upDatas = {
                    goodsId:_id,
                    goodsState:1
                }
                baseFn.dialog({
                    title:'上架商品',
                    content:'确定上架该商品么？',
                    ok:function(){
                        $.post(baseUrl.base+baseUrl.init+'updateGoodsInfo',_upDatas,function(res){
                            var _txt = '上架成功'
                            if(res.code == 0){
                                _txt = '上架成功';
                                var _d = goods.row(_tr).data()
                                _d.goodsState=1
                                goods.row(_tr).data(_d).draw(false)
                            }else{
                                _txt = res.info
                            }
                            baseFn.infoDialog(_txt)
                        },'json')
                    },
                    cancel:true
                })
            })
            $('.edit').off('click').on('click',function(){
                var _id = $(this).data('vals')
                // baseFn.setDTPage('goodslist',goods.page.info().page+1) //记录翻页（服务器不分页）
                window.location.href=DocData.editURL+"?goodsId="+_id
            })
            //图片初始化
            $('.js_goods_list .datatable_img_div').each(function(ids,val){
                baseFn.imgSize({
                    src: $(val).data('vals'),
                    hFn: function(res) {
                        res.dom.css({'background-size':'auto 100%'})
                    },
                    wFn: function(res) {
                        res.dom.css({'background-size':'100% auto'})
                    },
                    ratio: 1,
                    otherData: {
                        dom:$(val)
                    }
                })
            })
        },
        init:function(dt){
            // dt.page(baseFn.getDTPage('goodslist')-1).draw(false) //获取翻页（服务器不分页）
        }
    })
    $('.zcsearch_btn').on('click',function(val){
        var _txt =$.trim($(this).siblings('input.zcsearch_input').val());
        $.session.set("goodName",_txt);
        //if(_txt != ''){
            goods.settings()[0].ajax.data={
                goodsName:_txt
            }
            goods.ajax.reload()
        //}
    })
    $("input.zcsearch_input").keydown(function(event) {
        if (event.keyCode == "13") {
            var _txt =$.trim($(this).val());
            $.session.set("goodName",_txt);
            goods.settings()[0].ajax.data={
                goodsName:_txt
            }
            goods.ajax.reload()
        }
    });
}
if($('.js_goods_cost').length != 0){
    var _upData={
        subclinicId:SessionData.powerSub?SessionData.powerSub:0,//权限管理 45 全部门店
        ifMonth:0,
        orderTime:baseFn.timestampToTime(Date.parse(new Date())).substring(0,10)
    }
    var goodscost =''
    baseFn.rpSelect('.subclinic',{
        url:baseUrl.base+baseUrl.subclinic+'selectSubclinicList',
        idKey:'subclinicId',
        textKey:'subclinicName',
        calFn:function(){
            //权限管理 45 全部门店
            if(SessionData.powerSub){
                $(".subclinic").val(SessionData.powerSub).trigger('change')
            }
        },
        selFn:function(){
            searchingList()
        }
    })
    $('.timetype').change(function(){
        searchingList()
    })
    function searchingList(){
        var _upData = {
            subclinicId:$('.subclinic').val(),
            ifMonth:$('.timetype').val(),
            orderTime:$('.timeday').val()
        }
        DocData.initGoodsCostList(_upData)
        if(goodscost != ''){
            DocData.initGoodsCostDetail(_upData)
        }

    }
    baseFn.dateTimePick('.js_datepicker',{
        onSelectDate:searchingList
    })
    $('.js_datepicker').val(baseFn.timestampToTime(Date.parse(new Date())).substring(0,10))
    DocData.initGoodsCostList(_upData)
    $('.js_detail').on('click',function(){
        var _upData={
            subclinicId:$('.subclinic').val(),
            ifMonth:$('.timetype').val(),
            orderTime:$('.timeday').val()
        }
        if(goodscost == ''){
            DocData.initGoodsCostDetail(_upData)
        }
        $('.js_goodscost_main').addClass('hidden')
        $('.js_goodscost_detail').removeClass('hidden')
        $('.js_return_wrap').removeClass('hidden')
    })
    $('.js_return').on('click',function(){
        $('.js_goodscost_main').removeClass('hidden')
        $('.js_goodscost_detail').addClass('hidden')
        $('.js_return_wrap').addClass('hidden')
    })
}
//表格自适应
window.onresize = function(){
    windowOffsetData.refresh();
    if($('.js_goods_list').length != 0){
        $(goods.table().body()).parents('.dataTables_scrollBody').css('max-height',windowOffsetData.tableHeight());
        goods.draw(false);
    }
    if($('.js_goods_cost').length != 0){
        $(goodscost.table().body()).parents('.dataTables_scrollBody').css('max-height',windowOffsetData.tableHeight());
        goodscost.draw(false);
    }

}

